package com.apes.fn.scm.commodityInquiry.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.fixedLoss.modle.LossQuotation;
import com.apes.fn.business.fixedLoss.repository.LossQuotationItemRepository;
import com.apes.fn.business.fixedLoss.repository.LossQuotationRepository;
import com.apes.fn.business.fixedLoss.service.LossQuotationService;
import com.apes.fn.scm.commodityInquiry.model.ExternalInquiry;
import com.apes.fn.scm.commodityInquiry.model.ExternalInquiryItem;
import com.apes.fn.scm.commodityInquiry.repository.ExternalInquiryDao;
import com.apes.fn.scm.commodityInquiry.repository.ExternalInquiryItemRepository;
import com.apes.fn.scm.commodityInquiry.repository.ExternalInquiryRepository;
import com.apes.fn.server.productRequire.ProductRequireRepository;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.server.servicePlan.service.ServicePlanceService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.account.account.model.Stock;
import com.apes.scm.account.account.repository.StockRepository;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("externalInquiryService")
public class ExternalInquiryService extends DomainService {

    @Autowired
    ExternalInquiryRepository externalInquiryRepository;
    @Autowired
    ExternalInquiryItemRepository externalInquiryItemRepository;
    @Autowired
    ServicePlanRepository servicePlanRepository;
    @Autowired
    LossQuotationRepository lossQuotationRepository;
    @Autowired
    ServicePlanceService servicePlanService;
    @Autowired
    LossQuotationService lossQuotationService;
    @Autowired
    PiManager piManager;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    StockRepository stockRepository;
    @Autowired
    ProductRequireRepository productRequireRepository;
    @Autowired
    ExternalInquiryDao externalInquiryDao;
    @Autowired
    DeptRepository deptRepository;
    @Autowired
    ServicePlanItemRepository servicePlanItemRepository;
    @Autowired
    LossQuotationItemRepository lossQuotationItemRepository;
    @Autowired
    CommodityInquiryOrderService commodityInquiryOrderService;
    @Autowired
    ProductRepository productRepository;
    @Autowired
    private BusinessParamRepository businessParamRepository;





    /***
     * 创建(自动转OA)
     */
    public ExternalInquiry transApprove(SimpleRequest request) {
        ExternalInquiry externalInquiry = request.getO(ExternalInquiry.class);
        if ("backInquiry".equals(externalInquiry.getState())) {
            for (ExternalInquiryItem externalInquiryItem : externalInquiry.getExternalInquiryItems())
                externalInquiryItem.setInquiryReason("");
        }
        saveCheckStock(externalInquiry); //保存的时候验证库存数量是否满足
//        saveCheckInnerQuiry(externalInquiry); //保存的时候验证库存数量是否满足
        externalInquiry.setState("transApprove");
        deleteNoChecked(externalInquiry);
        checkBrand(externalInquiry);//检查品质是否需要品牌
        checkData(externalInquiry);
        externalInquiry.setNextDisposeSign(String.valueOf(((User) getCurrentUser(request)).getId()));  //设置客诉节点的审批人
        PartyRole person = request.getPerson();
        User user =SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id",person.getId())).stream().findFirst().orElse(null);

        externalInquiry = externalInquiryRepository.saveAndFlush(externalInquiry);

        Model model = getSourceOrder(externalInquiry);
        if (model == null) throw new RuntimeException("未找到来源单据，请确认");
        if (model instanceof ServicePlan) {
            servicePlanService.addServicePlanLogger((ServicePlan) model,"发起外采询价单","",user);
        }

        return externalInquiry;
    }

    private void saveCheckInnerQuiry(ExternalInquiry externalInquiry) {

        List<ExternalInquiryItem> exList = externalInquiry.getExternalInquiryItems().stream().filter(externalInquiryItem -> {
            return externalInquiryItem.isInquirySelectState();
        }).collect(Collectors.toList());
        List<String> paramList =  exList.stream().map(externalInquiryItem -> {
            return externalInquiryItem.getProduct().getId();
        }).collect(Collectors.toList());
        if(paramList.size() == 0) throw new RuntimeException("无勾选项目");

        Map paramMap = MapUtil.mapper("SOURCE_BUSINESS_KEY",externalInquiry.getSourceBusinessKey()
                ,"SOURCE_BUSINESS_TYPE",firstToLower(externalInquiry.getSourceBusinessType()),
                "PRODUCT_ID",paramList);
        List<Map> result = this.invoke("scm.externalInquiry.queryCommodityInquiryProduct",paramMap);
        //过滤出未询过价格的商品
        List<ExternalInquiryItem> externalInquiryItems =exList.stream().filter(externalInquiryItem -> {
            String product_id = externalInquiryItem.getProduct().getId();
            return result.stream().filter(map ->{
                Map mapItem = (Map)map;
                return Objects.equals(mapItem.get("SOURCE_BUSINESS_TYPE"),firstToLower(externalInquiry.getSourceBusinessType()))
                        && Objects.equals(mapItem.get("SOURCE_BUSINESS_KEY"),externalInquiry.getSourceBusinessKey())
                        && Objects.equals(mapItem.get("PRODUCT_ID"),product_id);
            }).collect(Collectors.toList()).size() == 0 ? true : false;
        }).collect(Collectors.toList());
        //报错提示
        if(externalInquiryItems.size()> 0) throw new RuntimeException(externalInquiryItems.stream().map(externalInquiryItem -> {
            return "("+externalInquiryItem.getProduct().getId()+")"+ externalInquiryItem.getProduct().getName();
        }).collect(Collectors.joining(",","","")) + "未内部询价，不允许外采!");

    }

    private String firstToLower(String str){
        return str.substring(0,1).toLowerCase() + str.substring(1);
    }

    /**
     * 检查外采商品是否需要输入品质
     * @param externalInquiry
     */
    private void checkBrand(ExternalInquiry externalInquiry){

        String[] needBrand = {"国际品牌","国内品牌","再制造件"};
        externalInquiry.getExternalInquiryItems().stream().forEach(externalInquiryItem -> {
            if (externalInquiryItem.getProductQuality()==null)throw new RuntimeException("外采商品品质不能为空");
            String quality = externalInquiryItem.getProductQuality().getDescription();
            for (String name : needBrand) {
                if (quality.equals(name)){
                    if(externalInquiryItem.getProductBrand()==null||"".equals(externalInquiryItem.getProductBrand()))throw new RuntimeException("请输入外采商品的具体品牌");
                }
            }
        });
    }
    /**
     * 新增的时候验证是否能够进行该操作
     * @param externalInquiry
     */
    private void saveCheckStock(ExternalInquiry externalInquiry) {
        //存在库存充足的，不允许外采（保证来源是方案，并且是确认前的外采）
        ServicePlan servicePlan = servicePlanRepository.findOne(externalInquiry.getSourceBusinessKey());
        if("ServicePlan".equals(externalInquiry.getSourceBusinessType()) && servicePlan != null && servicePlan.getConfirmDate() == null){
            List<ExternalInquiryItem> externalInquiryItems = externalInquiry.getExternalInquiryItems().stream().filter(externalInquiryItem -> {
                Integer i = getStock(SpringManager.getBean(StockRepository.class).findByProductAndLocation(externalInquiryItem.getProduct(),externalInquiryItem.getLocation()));
                return i >= externalInquiryItem.getSaleQty() &&  externalInquiryItem.isInquirySelectState(); //销售数量大于库存数量，则返回
            }).collect(Collectors.toList());
            if(externalInquiryItems.size()> 0) throw new RuntimeException(externalInquiryItems.stream().map(externalInquiryItem -> {
                return "("+externalInquiryItem.getProduct().getId()+")"+ externalInquiryItem.getProduct().getName();
            }).collect(Collectors.joining(",","","")) + "商品库存充足，不允许外采!");
        }



    }


    /***
     * 退回
     */
    public ExternalInquiry backInquiry(SimpleRequest request) {
        ExternalInquiry externalInquiry = externalInquiryRepository.findOne((String) request.get("id"));
        externalInquiry = writeAnswer(externalInquiry, request);
        externalInquiry.setState("backInquiry");
        externalInquiry.setBackId(request.getPerson());
        externalInquiry.setBackDate(new Date());
        return externalInquiryRepository.saveAndFlush(externalInquiry);
    }

    /***
     * 待确认
     */
    public ExternalInquiry waitConfirm(SimpleRequest request) {
        ExternalInquiry externalInquiry = request.getO(ExternalInquiry.class);
        externalInquiry = writeAnswer(externalInquiry, request);
        externalInquiry.setState("waitConfirm");
        return externalInquiryRepository.saveAndFlush(externalInquiry);
    }

    /***
     * 审核
     */
    public ExternalInquiry approve(SimpleRequest request) {
        ExternalInquiry externalInquiry = request.getO(ExternalInquiry.class);
        externalInquiry.setState("approve");
        externalInquiry.setApproveId(request.getPerson());
        externalInquiry.setApproveDate(new Date());

        // 计算有效期止
        BusinessParam externalInquiryPrice = businessParamRepository.findAllByQueryKey("externalInquiryPrice").get(0);
        String valiePreiod = this.caclStatetime(Integer.valueOf(externalInquiryPrice.getValue()));

        // 获取销售单价
        externalInquiry.getExternalInquiryItems().forEach(requireItem -> {
            Map getPriceCondi = MapUtil.mapper("BRAND_ID", requireItem.getProduct().getBrand().getId(), "CLASSIFY_ID", requireItem.getProduct().getClassify().getId(), "P001", requireItem.getPurchaseUnit());
            JSONObject priceObj = this.newSystemPriceInner(new JSONObject(getPriceCondi));
            requireItem.setPriceUnit(priceObj.getDoubleValue("XSDJ"));
            requireItem.setPriceLimit(priceObj.getDoubleValue("XSXJ"));
            requireItem.setValidPeriod(DateUtil.parse(valiePreiod, DateUtil.SHOW_DATETIME_FORMAT));
            requireItem.setDownCompanyPurchasePrice(requireItem.getPurchaseUnit());
        });


        return externalInquiryRepository.saveAndFlush(externalInquiry);
    }

    public String caclStatetime(int day) {
        BusinessParam externalInquiryPrice = businessParamRepository.findAllByQueryKey("externalInquiryPrice").get(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, +Integer.valueOf(externalInquiryPrice.getValue()));

        Date monday = c.getTime();
        String preMonday = sdf.format(monday);
        return preMonday;
    }

    //写入响应时间，如果已经写过了，不会再写
    public ExternalInquiry writeAnswer(ExternalInquiry externalInquiry, SimpleRequest request){
        Map<String,Object> externalInquiryAnswer = externalInquiryRepository.findOneAnswer(externalInquiry.getId());
        if (Objects.isNull(externalInquiryAnswer.get("ANSWER_ID")) && Objects.isNull(externalInquiryAnswer.get("ANSWER_DATE"))){
            externalInquiry.setAnswerId(request.getPerson());
            externalInquiry.setAnswerDate(new Date());
            return externalInquiry;
        }
        return externalInquiry;
    }

    /***
     * 新系统价格
     */
    private JSONObject newSystemPriceInner(JSONObject condi) {
        condi.put("conditionStrategyId", "CG03");
        condi.put("SYS_RQ", new Date());
        JSONObject getPriceObj = JSONObject.parseObject(this.invoke("condition.execConditionStrategy", condi).toString());

        JSONObject returnData = new JSONObject();
        returnData.put("XSDJ", getPriceObj.getString("XSDJ"));
        returnData.put("XSXJ", getPriceObj.getString("XSXJ"));
        return returnData;
    }

    // 供外部调用
    public JSONObject newSystemPrice(SimpleRequest request) {
        return this.newSystemPriceInner(request.getJO());
    }

    /***
     * 取消
     */
    public ExternalInquiry cancel(SimpleRequest request) {

        ExternalInquiry externalInquiry = request.getO(ExternalInquiry.class);
        externalInquiry.setState("cancel");
        externalInquiry.setCancelId(request.getPerson());
        externalInquiry.setCancelDate(new Date());
        PartyRole person = request.getPerson();
        User user =SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id",person.getId())).stream().findFirst().orElse(null);

        Model model = getSourceOrder(externalInquiry);
        if (model == null) throw new RuntimeException("未找到来源单据，请确认");
        if (model instanceof ServicePlan) {
            servicePlanService.addServicePlanLogger(model,"外采询价单退回","",user);
        }
        return externalInquiryRepository.saveAndFlush(externalInquiry);
    }

    // 外采 - 详情接口
    public Map mergeResult(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        String sourceBusinessType = getJO.getString("sourceBusinessType");
        Map result = null;
        if ("LossQuotation".equalsIgnoreCase(sourceBusinessType)){
            result = invoke("fn.priceForwardService.mergeResult", MapUtil.mapped(lossQuotationRepository.findOne(getJO.getString("sourceBusinessKey"))));
        } else if ("ServicePlan".equalsIgnoreCase(sourceBusinessType)) {
            result = invoke("fn.priceForwardService.mergeResult", MapUtil.mapped(servicePlanRepository.findOne(getJO.getString("sourceBusinessKey"))));
        } else {
            throw new RuntimeException("未知单据类型，请联系开发人员处理！");
        }
        result.put("sign", false); // 闪电报价弹出界面隐藏勾选
        return result;
    }

    
    /***
     * 校验数据(判断是否填入采购价格以及询价原因)
     */
    private void checkData(ExternalInquiry externalInquiry) {

        if (externalInquiry.getCustomerExpand() == null || (externalInquiry.getCustomerExpand().getVin() == null))
            throw new RuntimeException("当前车辆不存在对应的车架号，请在App线上补全");

        if (externalInquiry.getCustomerExpand() == null || (externalInquiry.getCustomerExpand().getJekunModelCode() == null))
            throw new RuntimeException("当前车辆不存在对应的配置车型，请在App线上补全");

        externalInquiry.getExternalInquiryItems().forEach(externalInquiryItem -> {

            if ( StringUtils.isEmpty(externalInquiryItem.getInquiryReason()) && externalInquiryItem.getInquiryReasonType() == null)
                throw new RuntimeException("勾选项目存在未添加询价原因的商品，商品名称：" + externalInquiryItem.getProduct().getName() + "。 请补全对应商品的采购价格和询价原因以及门店备注");
            if (externalInquiryItem.getPurchaseUnit() == 0)
                throw new RuntimeException("勾选项目存在采购价格为零的商品，商品名称：" + externalInquiryItem.getProduct().getName() + "。 请补全对应商品的采购价格和询价原因以及门店备注");
            if (StringUtils.isEmpty(externalInquiryItem.getDeptRemark()))
                throw new RuntimeException("勾选项目存在采未添加门店备注的商品，商品名称：" + externalInquiryItem.getProduct().getName() + "。 请补全对应商品的采购价格和询价原因以及门店备注");

        });
    }

    /***
     * 删除没选中的商品
     */
    private void deleteNoChecked(ExternalInquiry externalInquiry) {
        externalInquiry.getExternalInquiryItems();

        Iterator<ExternalInquiryItem> iterator = externalInquiry.getExternalInquiryItems().iterator();
        while (iterator.hasNext()) {
            ExternalInquiryItem item = iterator.next();
            if (!item.isInquirySelectState()) iterator.remove();
        }
        if (externalInquiry.getExternalInquiryItems().size() == 0) throw new RuntimeException("请选择需外部询价的商品");
    }


    /***
     * 判断是否需要走服务方案正常流程
     */
    public <T extends Model> T getSourceOrder(ExternalInquiry externalInquiry) {
        if (externalInquiry.getSourceBusinessType().equals("ServicePlan")) {
            return (T) servicePlanRepository.findOne(externalInquiry.getSourceBusinessKey());
        } else {
            return (T) lossQuotationRepository.findOne(externalInquiry.getSourceBusinessKey());
        }
    }


    /***
     * 构建
     */
    private JSONObject prepareWriteBack(ExternalInquiry externalInquiry) {
        JSONObject mainJson = new JSONObject();
        mainJson.put("PTID", externalInquiry.getPlatform().getId());
        mainJson.put("GSID", externalInquiry.getCompany().getId());
        mainJson.put("sourceBusinessKey", externalInquiry.getSourceBusinessKey());
        mainJson.put("XJWCZT", "1");  // 标记当前为询价完成
        JSONArray spxdmx = externalInquiry.getExternalInquiryItems().stream().map(externalInquiryItem -> {

            JSONObject item = new JSONObject();
            item.put("SPID", externalInquiryItem.getProduct().getId());
            item.put("XJDH", externalInquiry.getId());
            item.put("CGZZID", "1007");
            item.put("CGZZMC", "广州市车宝网络科技有限公司");
            item.put("JLDW", externalInquiryItem.getUom().getName());
            item.put("PTID", externalInquiry.getPlatform().getId());
            item.put("GSID", externalInquiry.getCompany().getId());
            item.put("XSDJ", externalInquiryItem.getPriceUnit());
            item.put("XSXJ", externalInquiryItem.getPriceLimit());
            item.put("CGDJ", externalInquiryItem.getPurchaseUnit());
            item.put("XYGSCGJ", externalInquiryItem.getDownCompanyPurchasePrice());
            item.put("XSSL", externalInquiryItem.getSaleQty());

            return item;
        }).collect(Collectors.toCollection(JSONArray::new));

        mainJson.put("PUR_SPXJDMX", spxdmx);
        return mainJson;
    }
    /***
     * 确认方案构建
     */
    private JSONObject prepareWriteBack(ExternalInquiry externalInquiry,ServicePlan servicePlan) {
        List<ServicePlanItem> servicePlanItems = servicePlan.getServicePlanItems();
        JSONObject mainJson = new JSONObject();
        mainJson.put("PTID", externalInquiry.getPlatform().getId());
        mainJson.put("GSID", externalInquiry.getCompany().getId());
        mainJson.put("sourceBusinessKey", externalInquiry.getSourceBusinessKey());
        mainJson.put("XJWCZT", "1");  // 标记当前为询价完成
        JSONArray spxdmx = externalInquiry.getExternalInquiryItems().stream().map(externalInquiryItem -> {

            JSONObject item = new JSONObject();
            item.put("SPID", externalInquiryItem.getProduct().getId());
            item.put("XJDH", externalInquiry.getId());
            item.put("CGZZID", "1007");
            item.put("CGZZMC", "广州市车宝网络科技有限公司");
            item.put("JLDW", externalInquiryItem.getUom().getName());
            item.put("PTID", externalInquiry.getPlatform().getId());
            item.put("GSID", externalInquiry.getCompany().getId());
            ServicePlanItem servicePlanItem = new ServicePlanItem();
            for (int i = 0; i < servicePlanItems.size(); i++) {
                boolean productId = servicePlanItems.get(i).getProduct().getId().equals(externalInquiryItem.getProduct().getId());
                if (productId)  servicePlanItem=servicePlanItems.get(i);
            }
            item.put("XSDJ", servicePlanItem.getPriceUnit());
            item.put("XSXJ", servicePlanItem.getFloorPrice());
            item.put("CGDJ", externalInquiryItem.getPurchaseUnit());
            item.put("XYGSCGJ", externalInquiryItem.getDownCompanyPurchasePrice());
            item.put("XSSL", externalInquiryItem.getSaleQty());

            return item;
        }).collect(Collectors.toCollection(JSONArray::new));

        mainJson.put("PUR_SPXJDMX", spxdmx);
        return mainJson;
    }

    /***
     * 判断是否可生成要货单
     * 1. 服务方案已质检，终止，收款完成
     * 2. 明细行已被终止
     */
    public void checkProductRequireCreate(ExternalInquiry externalInquiry, ServicePlan servicePlan) {
        if (!servicePlan.getState().equals("confirm")) throw new RuntimeException("当前服务方案不为确认状态，请确认");

        externalInquiry.getExternalInquiryItems().forEach(externalInquiryItem -> {

            List<ServicePlanItem> servicePlanItems = servicePlan.getServicePlanItems().stream().filter(servicePlanItem ->
                    servicePlanItem.getProduct().getId().equals(externalInquiryItem.getProduct().getId()) && (servicePlanItem.getTerminationDate() != null || servicePlanItem.getQualityTestDate() != null))
                    .collect(Collectors.toCollection(ArrayList::new));

            if (servicePlanItems.size() != 0)
                throw new RuntimeException("当前商品在服务方案已被终止或质检，商品名称：" + externalInquiryItem.getProduct().getName());
        });
    }


    /***
     * 1.获取历史询价
     * 2.获取库存
     * 3. 获取要货数据
     */
    public JSONObject getReferenceInformation(SimpleRequest request) {

        JSONObject referenceInfo = new JSONObject();

        JSONObject param = request.getJO();

        referenceInfo.put("inquiryInfo", getInquiryInformation(param));
        referenceInfo.put("stockInfo", getStock(param));
//        referenceInfo.put("stockInfo", getProductStockInfo(request));
        referenceInfo.put("requireTrack", getRequireTrack(param));
        referenceInfo.put("inquiryPool", getInquiryPool(param));
        return referenceInfo;

    }

    /**
     * 获取商品库存信息
     * @param request
     * @return
     */
    public Page<Map> getProductStockInfo(SimpleRequest request){
        JSONObject param = request.getJO();
        String sourceBusinessKey = param.getString("sourceBusinessKey");

        List<Map> filters = request.get("condition");
        JSONObject conditionModel = new JSONObject();
        if("LossQuotation".equals(param.getString("sourceBusinessType"))) {
            LossQuotation lossQuotation = lossQuotationRepository.findOne(sourceBusinessKey);
            conditionModel.putAll(JSONObject.parseObject(JSONObject.toJSONString(lossQuotation)));
        } else {
            ServicePlan serviceplan = servicePlanRepository.findAll(JpaDsl.toCriteriaByEq("id",sourceBusinessKey)).stream().findFirst().get();
            conditionModel.putAll(JSONObject.parseObject(JSONObject.toJSONString(serviceplan)));
        }
        conditionModel.put("emitEvent",true);
        conditionModel.put("publicPage",true);

//        return MapUtil.mapper("condition",filters,"conditionModel",conditionModel,"size",20,"page",0,"queryStock",true);
        Page<Map> invoke = this.invoke("cm.product.findProductByServicePlan", MapUtil.mapper("condition", filters, "conditionModel", conditionModel, "size", request.get("size"), "page", request.get("page"), "queryStock", true));
        for (Map map : invoke.getContent()) {
           String newName="["+ map.get("id").toString()+"]"+map.get("name").toString();
           map.put("name",newName);
        }
        return invoke;
    }
    public JSONObject getProductStockInfoPrice(SimpleRequest request){
        JSONObject productPrice = findProductPrice(request);
        JSONObject price = new JSONObject();
        double referTax = productPrice.getDoubleValue("referTax");
        BigDecimal b = new BigDecimal(referTax);
        price.put("referTax",b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        return price;
    }
    /**
     * 根据商品id和来源找价格
     * @param request
     * @return
     */
    public JSONObject findProductPrice(SimpleRequest request){
        JSONObject param = request.getJO();
        Product product = productRepository.findOne(param.getString("productId"));
        String sourceBusinessKey = param.getString("sourceBusinessKey");
        if("LossQuotation".equals(param.getString("sourceBusinessType"))) {
            LossQuotation lossQuotation = lossQuotationRepository.findOne(sourceBusinessKey);
            return this.invoke("fn.fixedLoss.getPrice", MapUtil.mapper("condition",JSONObject.toJSONString(product),"conditionModel",JSONObject.toJSONString(lossQuotation)));
        } else {
            ServicePlan serviceplan = servicePlanRepository.findAll(JpaDsl.toCriteriaByEq("id",sourceBusinessKey)).stream().findFirst().get();
            return this.invoke("fn.service.getPrise", MapUtil.mapper("condition",JSONObject.toJSONString(product),"conditionModel",JSONObject.toJSONString(serviceplan)));
        }
    }
    /**
     * 获取询价数据
     */
    private JSONObject getInquiryInformation(JSONObject param) {
        JSONObject row =  param.getJSONObject("node");
        String id = null; // 询价单号
        Map queryMap = MapUtil.mapper(
                "ID", param.getString("sourceBusinessKey"),
                "PRODUCT_ID", row.getJSONObject("product").getString("id")
        );

        // 获取原询价单号
        if (param.getString("sourceBusinessType").equals(LossQuotation.class.getSimpleName())){
            id = externalInquiryDao.getLossQuotationItemInquiry(queryMap);
        } else {
            id = externalInquiryDao.getServicePlanItemInquiry(queryMap);
        }

        // 构建返回结构
        if (id == null) return new JSONObject(MapUtil.mapper(
                "item", new ArrayList()
        ));

        SimpleRequest request = new SimpleRequest();
        request.setData(MapUtil.mapper(
                "id", id
        ));
        return commodityInquiryOrderService.queryWCBJGysxjdmx(request);
    }

    /***
     * 获取库存
     */
    private JSONObject getStock(JSONObject param) {
        JSONObject retrunJson = new JSONObject();
        Dept dept = deptRepository.findOne(param.getJSONObject("dept").getString("id"));
        Map condition = MapUtil.mapper(
                "NEW_DEPT_ID", dept.getId(),
                "OLD_DEPT_ID", dept.getOrigin(),
                "PRODUCT_ID", param.getJSONObject("node").getJSONObject("product").getString("id")
        );

        JSONArray stockQty = externalInquiryDao.getStock(condition);
        if (stockQty != null && stockQty.size() > 0) {
            JSONObject itemJson = stockQty.getJSONObject(0);
            retrunJson.put("stockAmount", itemJson.getDoubleValue("STOCK_AMOUNT")); //本地库存
            retrunJson.put("subStock", itemJson.getDoubleValue("SUB_STOCK")); //区域仓
            retrunJson.put("generalStock", itemJson.getDoubleValue("GENERAL_STOCK")); //总仓库存
        } else {
            retrunJson.put("stockAmount", 0); //本地库存
            retrunJson.put("subStock", 0); //区域仓
            retrunJson.put("generalStock", 0); //总仓库存
        }

        return retrunJson;
    }

    /***
     * 获取要货跟踪
     */
    private JSONArray getRequireTrack(JSONObject param) {
        JSONArray array = new JSONArray();

        Map condition = MapUtil.mapper(
                "SOURCE_BUSINESS_KEY", param.getString("sourceBusinessKey"),
                "SOURCE_BUSINESS_TYPE", param.getString("sourceBusinessType"),
                "PRODUCT_ID", param.getJSONObject("node").getJSONObject("product").getString("id")
        );

        JSONArray productRequire = externalInquiryDao.getProductRequire(condition);

        productRequire.stream().forEach(json -> {
            JSONObject response = piManager.synErp("ipmQueryYHDProcessService.queryYHDTrack", MapUtil.mapper("node", json));
            response = JSONObject.parseObject(response.get("obj").toString());
            response.put("title", ((JSONObject) json).getString("ID"));
            array.add(response);
        });
        return array;
    }

    /***
     * 更新参考信息
     */
    private ExternalInquiry updateRefer(ExternalInquiry externalInquiry) {

        SimpleRequest request = new SimpleRequest();
        externalInquiry.getExternalInquiryItems().stream().forEach(externalInquiryItem -> {

            request.setData(MapUtil.mapper(
                    "sourceBusinessKey", externalInquiry.getSourceBusinessKey(),
                    "sourceBusinessType", externalInquiry.getSourceBusinessType(),
                    "dept", MapUtil.mapper(
                            "id", externalInquiry.getDept().getId()
                    ),
                    "node", MapUtil.mapper(
                            "product", MapUtil.mapper(
                                    "id", externalInquiryItem.getProduct().getId()
                            )
                    )
            ));

            externalInquiryItem.setRefer(null);
            JSONObject information = getReferenceInformation(request);

            // 有库存
            if (information.getJSONObject("stockInfo").getDoubleValue("stockAmount") > 0.00
                    || information.getJSONObject("stockInfo").getDoubleValue("subStock") > 0.00
                    || information.getJSONObject("stockInfo").getDoubleValue("generalStock") > 0.00) {
                externalInquiryItem.addRefer("有库存");
            }

            // 询过价
            if (information.getJSONObject("inquiryInfo").getJSONArray("item").size() > 0) {
                externalInquiryItem.addRefer("询过价");
            }

            // 有要货
            if (information.getJSONArray("requireTrack").size() > 0) {
                externalInquiryItem.addRefer("有要货");
            }

            if (externalInquiryItem.getRefer() == null) externalInquiryItem.setRefer(null);

        });

        return externalInquiryRepository.saveAndFlush(externalInquiry);
    }


    /***
     * 查询数据供前端使用
     */
    public Map findOrderToInquiry(SimpleRequest request) {
        JSONObject param = request.getJO();

        if (param.getString("sourceType").equals(LossQuotation.class.getSimpleName())) {
            return findOneLossQuotation(param);
        } else {
            return findOneServicePlan(param);
        }

    }

    private Map findOneServicePlan(JSONObject param) {
        ServicePlan servicePlan = servicePlanRepository.findOne(param.getString("id"));
        return MapUtil.mapper(
                "supplier", MapUtil.mapper(
                        "id", "004465",
                        "name", "赋能门店现金外采"
                ),
                "platform", MapUtil.mapper(
                        "id", "1007",
                        "name", "广州市车宝网络科技有限公司"
                ),
                "sourceBusinessType", servicePlan.getInnerBusinessType(),
                "sourceBusinessKey", servicePlan.getId(),
                "sourceBusinessTypeName", servicePlan.getBusinessTypeName("innerBusinessType"),
                "company", servicePlan.getCompany(),
                "dept", servicePlan.getBelongDept(),
                "customerExpand", servicePlan.getFnCustomerExpand(),
                "sourceBusiness", "[服务方案]" + servicePlan.getId(),
                "externalInquiryItems", servicePlan.getServicePlanItems().stream().filter(servicePlanItem -> {
                    return servicePlanItem.isServiceState() && !servicePlanItem.isTerminationFlag() && servicePlanItem.getInquirySelectFlag() == 1 && (
                            (!servicePlanItem.getCategory().getId().equals("009525") && !servicePlanItem.isProductRule())
                                    || (!servicePlanItem.getCategory().getId().equals("009525") && servicePlanItem.isProductRule() && !servicePlan.getState().equals("confirm"))
                                    || (servicePlanItem.getCategory().getId().equals("009525") && servicePlanItem.isProductRule() && !servicePlan.getState().equals("confirm"))
                    );
                }).map(servicePlanItem -> {
                    return MapUtil.mapper(
                            "product", servicePlanItem.getProduct(),
                            "location", servicePlanItem.getLocation(),
                            "uom", servicePlanItem.getUom(),
                            "saleQty", servicePlanItem.getSaleQty(),
                            "inquirySelectState ", true,
                            "productRule", servicePlanItem.isProductRule(),
                            "mapAddress", servicePlanItem.getMapAddress(),
                            "category", servicePlanItem.getProduct().getCategory()
                    );
                }).collect(Collectors.toList())

        );
    }

    /**
     * 获取库存
     * @param stocks
     * @param productId
     * @param locationId
     * @return
     */
    private Integer getStock(List<Stock> stocks, String productId, String locationId) {
        Stock reStock = stocks.stream().filter(stock -> {
            return productId.equals(stock.getProduct().getId()) && locationId.equals(stock.getLocation().getId());
        }).findFirst().orElse(null);
        return reStock == null ? 0 : ((Double)(reStock.getMarketableQtyFa())).intValue();
    }

    /**
     * 获取库存
     * @return
     */
    private Integer getStock(Stock stock) {
        return stock == null ? 0 : ((Double)(stock.getMarketableQtyFa())).intValue();
    }

    private Map findOneLossQuotation(JSONObject param) {
        LossQuotation lossQuotation = lossQuotationRepository.findOne(param.getString("id"));
        return MapUtil.mapper(
                "supplier", MapUtil.mapper(
                        "id", "004465",
                        "name", "赋能门店现金外采"
                ),
                "platform", MapUtil.mapper(
                        "id", "1007",
                        "name", "广州市车宝网络科技有限公司"
                ),
                "sourceBusinessType", lossQuotation.getInnerBusinessType(),
                "sourceBusinessKey", lossQuotation.getId(),
                "sourceBusinessTypeName", lossQuotation.getBusinessTypeName("innerBusinessType"),
                "company", lossQuotation.getCompany(),
                "dept", lossQuotation.getFixedLossDept(),
                "customerExpand", lossQuotation.getCustomerExpand(),
                "sourceBusiness", "[定损报价]" + lossQuotation.getId(),
                "externalInquiryItems", lossQuotation.getLossQuotationItems().stream().filter(lossQuotationItem -> {
                    return lossQuotationItem.isAgree() && !lossQuotationItem.isReplaceWithRepair() && lossQuotationItem.getInquirySelectFlag() == 1 && (
                            !lossQuotationItem.getCategory().getId().equals("009525")
                                    || (lossQuotationItem.getCategory().getId().equals("009525") && lossQuotationItem.isProductRule())
                    );
                }).map(lossQuotationItem -> {
                    return MapUtil.mapper(
                            "product", lossQuotationItem.getProduct(),
                            "location", lossQuotationItem.getLocation(),
                            "uom", lossQuotationItem.getUom(),
                            "saleQty", lossQuotationItem.getSaleQty(),
                            "inquirySelectState ", true,
                            "productRule", lossQuotationItem.isProductRule(),
                            "mapAddress", lossQuotationItem.getMapAddress(),
                            "category", lossQuotationItem.getProduct().getCategory()
                    );
                }).collect(Collectors.toList())

        );
    }

    /**
     * 获取询价池数据
     * @param request
     * @return
     */
    public Object getInquiryPool(JSONObject request) {
        Map map = new HashMap<>();
        if("ServicePlan".equals(request.getString("sourceBusinessType"))) {
             map = MapUtil.mapped(SpringManager.getBean(ServicePlanRepository.class).findOne(request.getString("sourceBusinessKey")));
        } else {
            map = MapUtil.mapped(SpringManager.getBean(LossQuotationRepository.class).findOne(request.getString("sourceBusinessKey")));
        }
        map.put("platform", request.getString("platform"));
        return invoke("commodityInquiry.order.getInquiryPool", map);
    }

    public Map querySourceState(SimpleRequest request) {
        Map param = new HashMap();
        ExternalInquiry externalInquiry = request.getO(ExternalInquiry.class);
        if(externalInquiry.getSourceBusinessType().equals("ServicePlan")) {
            ServicePlan servicePlan = SpringManager.getBean(ServicePlanRepository.class).findOne(externalInquiry.getSourceBusinessKey());
            if ("confirm".equals(servicePlan.getState())) param.put("value", true);
            else  param.put("value", false);
        } else {
            LossQuotation lossQuotation = SpringManager.getBean(LossQuotationRepository.class).findOne(externalInquiry.getSourceBusinessKey());
            if ("create".equals(lossQuotation.getState()) ||
                "confirmPlan".equals(lossQuotation.getState()) ||
                "techAudit".equals(lossQuotation.getState()))  param.put("value", false);
            else  param.put("value", true);
        }
        return param;
    }

    // 闪电报价获取价格
    public List<JSONObject> lightningQuotationFindPrice(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        if (getJO.isEmpty()) throw new RuntimeException("获取报价入参个数为 0");

        List<ExternalInquiryItem> requireItems = externalInquiryItemRepository.findAll(
                JpaDsl.toCriteria(this.appendCondition(getJO))
        );

        // 把外采价格格式化成闪电报价格式
        List<JSONObject> inquiryPrices = new ArrayList<>();
        if (getJO.isEmpty()) throw new RuntimeException("获取报价结果入参值全部为空！");
        requireItems.forEach(inquiryItem -> {
            inquiryPrices.add(this.formatLightningQutotationData(inquiryItem));
        });
        return inquiryPrices;
    }

    private List<Map> appendCondition(JSONObject condi) {
        List<Map> conditions = new ArrayList<>();
        condi.forEach((k, v) -> {
            if (!StringUtils.isEmpty(v)) {
                conditions.add(MapUtil.mapper("field", k, "value", v, "operator", "EQ"));
            }
        });
        conditions.add(MapUtil.mapper("field", "externalInquiry.state", "value", "approve", "operator", "EQ"));
        conditions.add(MapUtil.mapper("field", "validPeriod", "value", new Date(), "operator", "GTE"));

        return conditions;
    }

    // 把外采价格格式化成闪电报价格式
    private JSONObject formatLightningQutotationData(ExternalInquiryItem inquiryItem) {
        JSONObject enquiryItem = new JSONObject();
        enquiryItem.put("classify", inquiryItem.getProduct().getClassify().getName());
        enquiryItem.put("notTaxUnitPrice", inquiryItem.getPurchaseUnit());//成本价
        enquiryItem.put("categoryName", inquiryItem.getProduct().getCategory().getName());//配件名称
        enquiryItem.put("selectFlag", 1);
        enquiryItem.put("productName", inquiryItem.getProduct().getName());// 标准名称
        enquiryItem.put("spProduct", MapUtil.mapper("id", inquiryItem.getProduct().getId(), "name", inquiryItem.getProduct().getName(), "valid", inquiryItem.getProduct().isValid()));
        enquiryItem.put("SPMC", inquiryItem.getProduct().getName());
        enquiryItem.put("MDID", inquiryItem.getExternalInquiry().getDept().getId());
        enquiryItem.put("supplier", inquiryItem.getExternalInquiry().getSupplier().getName());

        Enumeration logisticsMode = getBean(EnumerationRepository.class).findByTypeAndCode("logisticsMode", "merchant");
        enquiryItem.put("logisticsMode", MapUtil.mapper("id", logisticsMode.getId(), "name", logisticsMode.getDescription()));
        enquiryItem.put("id", inquiryItem.getProduct().getId());

        Enumeration supplyStatus = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("003334", "supplyStatus");
        enquiryItem.put("state", supplyStatus.getDescription());//货源
        enquiryItem.put("productRule", inquiryItem.isProductRule());
        enquiryItem.put("SPID", inquiryItem.getProduct().getId());
        enquiryItem.put("address", getBean(StoreRepository.class).findByDept(inquiryItem.getExternalInquiry().getDept()).getAddress());
        enquiryItem.put("logisticsModeItems", Arrays.asList(enquiryItem.get("logisticsMode")));
        enquiryItem.put("uniqueValue", inquiryItem.getExternalInquiry().getId() + inquiryItem.getId());
        enquiryItem.put("XSDJ", inquiryItem.getPriceUnit()); // 零售价
        enquiryItem.put("Brand", inquiryItem.getProductBrand()); // 品牌
        enquiryItem.put("taxUnitPrice", inquiryItem.getPurchaseUnit());
        enquiryItem.put("qualityName", inquiryItem.getProductQuality().getDescription());
        enquiryItem.put("priceSuggested", inquiryItem.getPriceUnit()); // 建议售价
        enquiryItem.put("name", inquiryItem.getProduct().getName());
        enquiryItem.put("WYZ", enquiryItem.getString("uniqueValue"));
        enquiryItem.put("category", inquiryItem.getProduct().getCategory().getName());
        enquiryItem.put("fitting", MapUtil.mapper("id", inquiryItem.getProduct().getCategory().getId(), "name", inquiryItem.getProduct().getCategory().getName()));
        enquiryItem.put("categoryId", inquiryItem.getProduct().getCategory().getId());
        enquiryItem.put("inquiryGooodsState", supplyStatus.getCode());
        enquiryItem.put("enquiryId", inquiryItem.getExternalInquiry().getId());
        return enquiryItem;
    }

    public boolean sourceConfirmPriceValid(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        Map validPrices = externalInquiryItemRepository.sourceQueryPriceValid(getJO.getString("id"), getJO.getString("unique"));
        return !validPrices.isEmpty();
    }
}
